import { store } from '../index'
import { defineStore } from 'pinia'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
import { TUIChatEngine, genTestUserSig } from '@/TUIKit'
import { TUIConversationService } from '@tencentcloud/chat-uikit-engine'

interface IMVO {
  userID: String
}

// im配置信息
const SDKAppID = 1600029298 // Your SDKAppID
const secretKey = 'fdb5b8018dfda4cedc7eacd833d709cfca144ea2e614217a3652cef0873f9cfa' //Your secretKey

export const useIMStore = defineStore('IM', {
  state: (): IMVO => ({
    userID: wsCache.get('IMUserID') || '1'
  }),
  getters: {
    getIMUserID(): String {
      return this.userID
    }
  },
  actions: {
    setIMUserID(userID) {
      this.userID = userID
    },
    async loginTIM(userID) {
      // 不允许重复登录
      if (TUIChatEngine.userID === userID) return

      // 登录 IM
      await TUIChatEngine.login({
        SDKAppID,
        userID,
        userSig: genTestUserSig({
          SDKAppID,
          secretKey,
          userID
        }).userSig,
        useUploadPlugin: true, // 使用文件上传插件
        useProfanityFilterPlugin: true // 使用本地审核插件
      })

      // 登录成功后进行相关业务逻辑处理
      console.log(`TIM 登录: ${userID}`, TUIChatEngine)
    },
    async logoutTIM() {
      if (TUIChatEngine.isInited) {
        // 清空当前会话ID
        await TUIConversationService.switchConversation('')

        // 登出 Chat SDK
        await TUIChatEngine.logout()

        // 登录成功后进行相关业务逻辑处理
        console.log(`TIM 登出: `, TUIChatEngine)
      }
    },
    async reLoginTIM(userID) {
      console.log('TIM 当前已登录:', TUIChatEngine)
      console.log('TUIChatEngine.userID', TUIChatEngine.userID)
      console.log('userID', userID)

      // 不允许重复登录
      if (TUIChatEngine.userID === userID) return

      // 登出 Chat SDK
      await this.logoutTIM()

      // 重新登录 IM
      await this.loginTIM(userID)
    }
  }
})

export const useIMStoreWithOut = () => {
  return useIMStore(store)
}
